<template>
  <div class="content" v-loading="pageLoading">
    <el-row type="flex" :gutter="20">
      <el-col :span="4" class="col-one">
        <el-card shadow="always">
          <!-- <div>
            <el-input
              placeholder="请输入内容"
              v-model="searchVal"
              class="input-with-select"
            >
              <el-button
                type="primary"
                slot="append"
                icon="el-icon-search"
              ></el-button>
            </el-input>
          </div> -->
          <div
            class="button-box"
            v-for="(item, index) in algoOprAry"
            :key="`${index + item.id}`"
          >
            <el-button @click="addOperator(item)">{{ item.optName }}</el-button>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="always">
          <div slot="header" class="button-group">
            <span>特征链</span>
            <el-button
              type="primary"
              circle
              v-if="!operatorSwitch"
              @click="handleOperatorSwitch"
            >
              <i class="iconfont icon-start-filled aside-icon"></i>
            </el-button>
            <el-button type="info" circle v-else @click="handleOperatorSwitch">
              <i class="iconfont icon-stop-line aside-icon"></i>
            </el-button>
          </div>
          <!-- 动态控件区 -->
          <div style="overflow: auto; height: 68vh">
            <div
              class="operator-box"
              v-for="item in dynamicOperatorList"
              :key="item.id"
            >
              <!-- 设置自定义属性operatorName -->
              <div
                class="operator"
                @dblclick="dynamicOperatorClick(item)"
                @click="showDataList(item, true)"
                :operatorId="item.id"
              >
                {{ item.operatorname }}
              </div>
              <div class="delete-operator" @click="deleteOperator(item)">x</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card shadow="always">
          <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
            <el-tab-pane label="运行日志" name="first">
              <!-- 这里放日志的内容 -->
              <console-component></console-component>
            </el-tab-pane>
            <el-tab-pane label="数据集" name="second">
              <el-table
                class="table"
                :data="modelTableData"
                style="width: 100%"
                v-loading="modelLoading"
                @selection-change="handleModelSelectionChange"
                @row-click="modelRowClick"
                ref="multipleTable"
              >
                <el-table-column type="selection" width="45"></el-table-column>
                <el-table-column label="序号" show-overflow-tooltip width="60">
                  <template slot-scope="scope">
                    <span
                      >{{
                        scope.$index +
                        (modelCurrentPage - 1) * modelPageSize +
                        1
                      }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  v-for="(item, index) in dataSetTitleList"
                  :key="index"
                  :label="item"
                  :prop="item"
                  show-overflow-tooltip
                >
                </el-table-column>
              </el-table>
              <mine-pagination
                @numberChange="modelNumberChange"
                :total="modelTotal"
                :page-size="modelPageSize"
                :current-page="modelCurrentPage"
              >
              </mine-pagination>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
    <!-- 弹框区 -->
    <mine-dialog
      :top="'10vh'"
      :dialogFormVisible="flag"
      :appendToBody="true"
      :width="'900px'"
      :showClose="true"
      :title="title"
      @close="close"
    >
      <InputOpera
        v-if="currentOperator === 'fileUpload'"
        slot="option"
        :flag="flag"
        @changeFlag="close"
        @getFileDataList="getFileDataList"
        :currentOperatorData="currentOperatorData"
        :currentProcessId="currentProcessId"
      ></InputOpera>
      <OutputOpera
        v-if="currentOperator === 'fileOut'"
        slot="option"
        :flag="flag"
        @changeFlag="close"
        :currentOperatorData="currentOperatorData"
        :fileDataList="fileDataList"
      ></OutputOpera>
      <Default
        v-if="currentOperator === 'missing'"
        slot="option"
        :flag="flag"
        @changeFlag="close"
        :currentOperatorData="currentOperatorData"
        :fileDataList="fileDataList"
        :missingConditionSelectionList="missingConditionSelectionList"
      ></Default>
      <Attrs
        v-if="currentOperator === 'attributecreate'"
        slot="option"
        :flag="flag"
        @changeFlag="close"
        :currentOperatorData="currentOperatorData"
        :fileDataList="fileDataList"
      ></Attrs>
      <Deduplication
        v-if="currentOperator === 'duplicate'"
        slot="option"
        :flag="flag"
        @changeFlag="close"
        :currentOperatorData="currentOperatorData"
        :fileDataList="fileDataList"
      ></Deduplication>
      <FilterOpera
        v-if="currentOperator === 'filter'"
        slot="option"
        :flag="flag"
        @changeFlag="close"
        :currentOperatorData="currentOperatorData"
        :fileDataList="fileDataList"
        :filterConditionSelectionList="filterConditionSelectionList"
      ></FilterOpera>
      <Pca
        v-if="currentOperator === 'pca'"
        slot="option"
        :flag="flag"
        @changeFlag="close"
        :currentOperatorData="currentOperatorData"
        :fileDataList="fileDataList"
      ></Pca>
      <Standard
        v-if="currentOperator === 'standard'"
        slot="option"
        :flag="flag"
        @changeFlag="close"
        :currentOperatorData="currentOperatorData"
        :fileDataList="fileDataList"
        :standardSelectionList="standardSelectionList"
      ></Standard>
    </mine-dialog>
  </div>
</template>

<script>
import InputOpera from "./Dialog/InputOpera";
import OutputOpera from "./Dialog/OutputOpera";
import Default from "./Dialog/Default";
import Attrs from "./Dialog/Attrs";
import Deduplication from "./Dialog/Deduplication";
import FilterOpera from "./Dialog/filterOpera";
import Pca from "./Dialog/Pca";
import Standard from "./Dialog/Standard";
import ConsoleComponent from "./components/Console.vue";
import { async } from "@antv/x6/lib/registry/marker/async";
import qs from "qs";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";
import lodash from "lodash";

export default {
  name: "algoFlow",
  components: {
    InputOpera,
    OutputOpera,
    Default,
    Attrs,
    Deduplication,
    FilterOpera,
    Pca,
    Standard,
    ConsoleComponent,
  },
  data() {
    return {
      searchVal: "",
      algoOprAry: [],
      activeName: "first",

      modelTableData: [], // 数据集列表的渲染数据
      dataSetTitleList: [], // 数据集列表的渲染行标题
      modelLoading: false,
      modelCurrentPage: 1,
      modelPageSize: 10,
      modelTotal: 0,
      currentItem: {}, // 当前点击的动态算子信息
      dynamicOperatorList: [], // 动态控件区
      currentOperator: "", // 当前选中的动态控件
      flag: false, // 是否打开弹框
      title: "", // 控件弹框中的标题
      operatorSwitch: false, // 特征链运行开关
      apiCount: 0, // 记录当前执行动态控件数组的控件
      buttonList: [], // 当前动态算子区的按钮dom集合
      currentOperatorData: {}, // 当前双击的算子数据
      currentProcessId: "", // 最近添加的一个文件上传后的算子id
      filterConditionSelectionList: [], // 控件中处理方式的所有下拉选项
      fileDataList: [], // 文件上传后获取的标题信息
      standardSelectionList: [], // 数据标准化下拉选项
      dataListTimer: null, // 数据集防抖定时器
      pageLoading: false, // 全屏的loading
    };
  },
  methods: {
    Search() {},
    handleClick() {},
    handleModelSelectionChange() {},
    modelRowClick() {},
    searchModelSubmit() {},
    // checkModel() {},
    modelNumberChange(val) {
      switch (val.flag) {
        case "pageSize":
          this.modelPageSize = val.pageSize;
          this.showDataList(this.currentItem);
          break;
        case "currentPage":
          this.modelCurrentPage = val.currentPage;
          this.showDataList(this.currentItem);
          break;
        default:
          break;
      }
    },
    // 添加算子
    async addOperator(item) {
      if (this.operatorSwitch) return; // 如果执行中则禁止操作
      // 第一个控件必须为文件上传
      if (
        this.dynamicOperatorList.length === 0 &&
        item.optCode !== "fileUpload"
      ) {
        return this.$message.warning("请选择文件上传！");
      }

      let newObj = {};

      if (this.dynamicOperatorList.length === 0) {
        newObj = {
          canvasId: this.$route.query.id,
          operatorType: item.optCode,
          operatorname: item.optName,
          pid: 0,
        };
      } else {
        newObj = {
          canvasId: this.$route.query.id,
          operatorType: item.optCode,
          operatorname: item.optName,
          pid: this.dynamicOperatorList[this.dynamicOperatorList.length - 1].id,
        };
      }
      // 接口部分
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/feOperator/save",
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: newObj,
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              if (item.optCode === "fileUpload") {
                _self.currentProcessId = result.data.id;
              }
              _self.dynamicOperatorList.push(result?.data);
            } else {
              _self.$message.warning("添加算子失败");
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/feOperator/save",
          "post",
          "application/json;charset=UTF-8",
          newObj,
          false,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            res = e.data.response;
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              if (item.optCode === "fileUpload") {
                this.currentProcessId = res.data.id;
              }
              this.dynamicOperatorList.push(res?.data);
            } else {
              this.$message.warning("添加算子失败");
            }
          },
          { once: true }
        );
      } else {
        res = await this.$store.dispatch("addDynamicOperator", newObj);
        if (res.data.status === 200) {
          if (item.optCode === "fileUpload") {
            this.currentProcessId = res.data.data.id;
          }

          this.dynamicOperatorList.push(res?.data?.data);
        } else {
          this.$message.warning("添加算子失败");
        }
      }
    },
    // 删除算子
    async deleteOperator(item) {
      if (this.operatorSwitch) return; // 如果执行中则禁止操作

      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/feOperator/deleteByIds${_self.$qwebUtil.convertIdsToQueryString(
                [item.id]
              )}`,
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: {},
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.dynamicOperatorList = _self.dynamicOperatorList.filter(
                (ele) => {
                  if (ele.id === item.id) {
                    return false;
                  }
                  return true;
                }
              );
            } else {
              _self.$message.warning(`${result.data.msg}`);
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/feOperator/deleteByIds${this.$webview2.convertIdsToQueryString([
            item.id,
          ])}`,
          "post",
          "application/json;charset=UTF-8",
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200) {
              this.dynamicOperatorList = this.dynamicOperatorList.filter(
                (ele) => {
                  if (ele.id === item.id) {
                    return false;
                  }
                  return true;
                }
              );
            } else {
              this.$message.warning(`${res.msg}`);
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("deleteOperator", {
          ids: [item.id],
        });
        if (res.data.status === 200) {
          this.dynamicOperatorList = this.dynamicOperatorList.filter((ele) => {
            if (ele.id === item.id) {
              return false;
            }
            return true;
          });
        } else {
          this.$message.warning(`${res.data.msg}`);
        }
      }
    },
    // 动态算子区点击事件
    dynamicOperatorClick(select) {
      if (this.operatorSwitch) return; // 如果执行中则禁止操作
      // 清理单击事件的定时器和事件
      clearTimeout(this.dataListTimer);
      this.pageLoading = true;
      // 每次双击更新控件左边列表数据
      setTimeout(async () => {
        await this.getFileDataList();
        // 保存当前双击的算子数据
        this.pageLoading = false;
        this.currentOperatorData = select;
        switch (select.operatorType) {
          case "fileUpload": {
            this.title = "文件上传";
            this.flag = true;
            this.currentOperator = "fileUpload";
            break;
          }
          case "missing": {
            this.title = "缺失值处理";
            this.flag = true;
            this.currentOperator = "missing";
            break;
          }
          case "filter": {
            this.title = "过滤处理";
            this.flag = true;
            this.currentOperator = "filter";
            break;
          }
          case "attributecreate": {
            this.title = "属性生成处理";
            this.flag = true;
            this.currentOperator = "attributecreate";
            break;
          }
          case "standard": {
            this.title = "数据标准化";
            this.flag = true;
            this.currentOperator = "standard";
            break;
          }
          case "duplicate": {
            this.title = "重复值处理";
            this.flag = true;
            this.currentOperator = "duplicate";
            break;
          }
          case "pca": {
            this.title = "主成分分析";
            this.flag = true;
            this.currentOperator = "pca";
            break;
          }
          case "fileOut": {
            this.title = "文件输出";
            this.flag = true;
            this.currentOperator = "fileOut";
            break;
          }
          default:
            break;
        }
      }, 600);
    },
    // 弹框关闭按钮
    close() {
      this.currentOperator = "";
      this.flag = false;
    },
    // 获取控件列表
    async getOperatorList() {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/dictionary/TreeList",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(
                { dirCode: "operatorType" },
                { indices: false }
              ),
              isStringParam: true,
              requestId: uuid,
            };

            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.getConditionSelection();
              _self.algoOprAry = result?.data[0].childrenParams;
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/dictionary/TreeList",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify({ dirCode: "operatorType" }, { indices: false }),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId == uuid) {
              this.getConditionSelection();
              this.algoOprAry = res?.data[0].childrenParams;
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("getOperatorList");
        if (res.status === 200) {
          this.getConditionSelection();
          this.algoOprAry = res?.data?.data[0].childrenParams;
        }
      }
    },
    // 特征链执行按钮
    async handleOperatorSwitch() {
      // 获取当前动态算子的所有按钮区域
      this.buttonList = document.querySelectorAll(".operator");

      // 显示日志页签
      this.activeName = "first";

      this.operatorSwitch = !this.operatorSwitch;
      if (this.operatorSwitch) {
        // 设置日志
        this.$store.commit("SET_CODE", "特征链启动...");
        const paramsList = this.dynamicOperatorList.map((item) => {
          return {
            id: item.id,
            operatorType: item.operatorType,
            optName: item.operatorname,
          };
        });
        paramsList.shift(); // 去掉第一个文件上传的控件
        this.reduceCall(paramsList);
      } else {
        // 设置日志
        this.$store.commit("SET_CODE", "特征链关闭");
        // 去掉高亮
        for (let i = 0; i < this.buttonList.length; i++) {
          this.buttonList[i].classList.remove("operator-active");
        }
      }
    },
    // 递归调用请求
    reduceCall(paramsList) {
      let that = this;
      if (paramsList.length > 0) {
        // console.log(that.execOperator(paramsList[1]));
        that.execOperator(paramsList[that.apiCount]).then(function (data) {
          that.apiCount++;
          if (that.apiCount < paramsList.length) {
            that.reduceCall(paramsList);
          } else {
            // 执行链完成后的操作
            that.apiCount = 0;
            that.operatorSwitch = false;
            // 设置日志
            that.$store.commit("SET_CODE", `特征链关闭`);
            // 去掉高亮
            for (let i = 0; i < that.buttonList.length; i++) {
              that.buttonList[i].classList.remove("operator-active");
            }
          }
        });
      } else {
        setTimeout(() => {
          that.operatorSwitch = false;
          // 设置日志
          that.$store.commit("SET_CODE", `特征链关闭`);
        }, 500);
      }
    },
    // 每次算子的执行请求
    execOperator(params) {
      let that = this;
      // 算子开始日志
      this.$store.commit("SET_CODE", `${params.optName}执行中...`);
      // 当前执行的算子高亮处理
      for (let i = 0; i < this.buttonList.length; i++) {
        this.buttonList[i].classList.remove("operator-active");
        if (this.buttonList[i].getAttribute("operatorId") == params.id) {
          this.buttonList[i].classList.add("operator-active");
        }
      }
      // 调用执行接口
      let _self = this;
      let res = {};
      let result = new Promise(async function (resolve, reject) {
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: "/feOperator/exec",
                RequestMethod: "post",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: params,
                isStringParam: false,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                // 算子结束日志
                _self.$store.commit("SET_CODE", `${params.optName}执行完毕`);
                resolve();
              } else {
                _self.$message.error(`${params.optName}执行失败`);
                _self.operatorSwitch = false;
                // 去掉高亮
                for (let i = 0; i < _self.buttonList.length; i++) {
                  _self.buttonList[i].classList.remove("operator-active");
                }
                _self.$store.commit("SET_CODE", `${params.optName}执行失败`);
              }
            });
          }
        } else if (that.$webview2.isWPF) {
          const uuid = that.$webview2.generateRandomUUID();
          await that.$webview2.sendWebView2(
            "/feOperator/exec",
            "post",
            "application/json;charset=UTF-8",
            params,
            false,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              // TODO： 定制后台数据处理
              if (res.status === 200) {
                // 算子结束日志
                that.$store.commit("SET_CODE", `${params.optName}执行完毕`);
                resolve();
              } else {
                that.$message.error(`${params.optName}执行失败`);
                that.operatorSwitch = false;
                // 去掉高亮
                for (let i = 0; i < that.buttonList.length; i++) {
                  that.buttonList[i].classList.remove("operator-active");
                }
                that.$store.commit("SET_CODE", `${params.optName}执行失败`);
              }
            },
            { once: true }
          );
        } else {
          const res = await that.$store.dispatch("execOperator", params);
          if (res.data.status === 200) {
            // 算子结束日志
            that.$store.commit("SET_CODE", `${params.optName}执行完毕`);
            resolve();
          } else {
            that.$message.error(`${params.optName}执行失败`);
            that.operatorSwitch = false;
            // 去掉高亮
            for (let i = 0; i < that.buttonList.length; i++) {
              that.buttonList[i].classList.remove("operator-active");
            }
            that.$store.commit("SET_CODE", `${params.optName}执行失败`);
          }
        }
      });
      return result;
    },
    // 单击显示对应算子的数据集结果
    async showDataList(item, refreshPage) {
      clearTimeout(this.dataListTimer);
      this.dataListTimer = setTimeout(async () => {
        if (this.operatorSwitch || ["fileOut"].includes(item.operatorType))
          return; // 如果执行中、点击文件上传或输出则禁止操作,
        // 保存当前显示数据集的算子数据
        this.currentItem = item;
        // 显示数据集页签
        this.activeName = "second";
        let res = {};
        let params = {
          id: item.id,
          pageSize: this.modelPageSize,
          page: this.modelCurrentPage,
        };
        // 点击算子时初始化传参
        if (refreshPage) {
          this.modelPageSize = 10;
          this.modelCurrentPage = 1;
        }
        // 获取算子的数据集内容
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: "/feOperator/getCacheById",
                RequestMethod: "get",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: qs.stringify(params, { indices: false }),
                isStringParam: true,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                _self.dataSetTitleList = Object.keys(result.data?.list[0]);
                _self.modelTableData = result?.data?.list || [];
                _self.modelTotal = result?.data?.rowCount;
              } else {
                _self.dataSetTitleList = [];
                _self.modelTableData = [];
                _self.modelTotal = 0;
                _self.$message.error("获取数据集失败");
              }
            });
          }
        } else if (this.$webview2.isWPF) {
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            "/feOperator/getCacheById",
            "get",
            "application/json;charset=UTF-8",
            qs.stringify(params, { indices: false }),
            true,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              // TODO： 定制后台数据处理
              if (res.status === 200 && e.data.webInfo.requestId === uuid) {
                this.dataSetTitleList = Object.keys(res.data?.list[0]);
                this.modelTableData = res?.data?.list || [];
                this.modelTotal = res?.data?.rowCount;
              } else {
                this.dataSetTitleList = [];
                this.modelTableData = [];
                this.modelTotal = 0;
                this.$message.error("获取数据集失败");
              }
            },
            { once: true }
          );
        } else {
          res = await this.$store.dispatch("getDataListById", params);
          if (res.data.status === 200) {
            this.dataSetTitleList = Object.keys(res.data.data.list[0]);
            this.modelTableData = res?.data?.data?.list || [];
            this.modelTotal = res?.data?.data?.rowCount;
          } else {
            this.modelTableData = [];
            this.$message.error(res.data.msg);
          }
        }
      }, 500);
    },
    // 获取 处理方式 和 数据标准化 的全部下拉选项
    async getConditionSelection() {
      // 根据单行类型获取过滤条件
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/dictionary/TreeList",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(
                {
                  dirCodes: "filter_",
                },
                { indices: false }
              ),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.filterConditionSelectionList = result.data;
            }
          });
        }

        setTimeout(async () => {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: "/dictionary/TreeList",
                RequestMethod: "get",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: qs.stringify(
                  {
                    dirCodes: "missing_",
                  },
                  { indices: false }
                ),
                isStringParam: true,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                _self.missingConditionSelectionList = result.data;
              }
            });
          }
        }, 200);

        setTimeout(async () => {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: "/dictionary/TreeList",
                RequestMethod: "get",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: qs.stringify(
                  {
                    dirCodes: "standard_",
                  },
                  { indices: false }
                ),
                isStringParam: true,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                _self.standardSelectionList = result.data[0].childrenParams;
              }
            });
          }
        }, 400);
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/dictionary/TreeList",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(
            {
              dirCodes: "filter_",
            },
            { indices: false }
          ),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let resFilter = e.data.response;
            // TODO： 定制后台数据处理
            if (resFilter.status === 200 && e.data.webInfo.requestId === uuid) {
              this.filterConditionSelectionList = resFilter.data;
            }
          },
          { once: true }
        );

        setTimeout(async () => {
          await this.$webview2.sendWebView2(
            "/dictionary/TreeList",
            "get",
            "application/json;charset=UTF-8",
            qs.stringify(
              {
                dirCodes: "missing_",
              },
              { indices: false }
            ),
            true
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let resMissing = e.data.response;
              // TODO： 定制后台数据处理
              if (resMissing.status === 200) {
                this.missingConditionSelectionList = resMissing.data;
              }
            },
            { once: true }
          );
        }, 200);

        setTimeout(async () => {
          await this.$webview2.sendWebView2(
            "/dictionary/TreeList",
            "get",
            "application/json;charset=UTF-8",
            qs.stringify(
              {
                dirCodes: "standard_",
              },
              { indices: false }
            ),
            true
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let resStandard = e.data.response;
              // TODO： 定制后台数据处理
              if (resStandard.status === 200) {
                this.standardSelectionList = resStandard.data[0].childrenParams;
              }
            },
            { once: true }
          );
        }, 400);
      } else {
        const resFilter = await this.$store.dispatch("getDicBydirCode", {
          dirCodes: "filter_",
        });
        if (resFilter.data.status === 200) {
          this.filterConditionSelectionList = resFilter.data.data;
        }
        const resMissing = await this.$store.dispatch("getDicBydirCode", {
          dirCodes: "missing_",
        });
        if (resMissing.data.status === 200) {
          this.missingConditionSelectionList = resMissing.data.data;
        }
        const resStandard = await this.$store.dispatch("getDicBydirCode", {
          dirCodes: "standard_",
        });
        if (resStandard.data.status === 200) {
          this.standardSelectionList = resStandard.data.data[0].childrenParams;
        }
      }
    },
    // 文件上传确定后再获取文件的行信息列表
    async getFileDataList() {
      return new Promise(async (resolve, reject) => {
        let params = {
          processingId: this.currentProcessId,
          types: "INTEGER,FLOAT",
        };

        let res = {};
        let _self = this;
        if (_self.$qwebUtil.isQtClient) {
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/feDatafile/getFieldTreeByProcessId?processingId=${_self.currentProcessId}&types=INTEGER,FLOAT`,
                RequestMethod: "get",
                ContentType: "application/json;charset=UTF-8",
                RequestBody: {},
                isStringParam: false,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              //       // console.error('received','/feCanvas/pageList')
            }
          );

          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              // sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                _self.fileDataList = result?.data;
                if (!_self.pageLoading) {
                  _self.getOperatorList();
                }
                resolve();
              } else {
                _self.$message.error("获取数据失败");
              }
            });
          }
        } else if (this.$webview2.isWPF) {
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            `/feDatafile/getFieldTreeByProcessId?processingId=${this.currentProcessId}&types=INTEGER,FLOAT`,
            "get",
            "application/json;charset=UTF-8",
            {},
            false,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              // TODO： 定制后台数据处理
              if (res.status === 200) {
                this.fileDataList = res?.data;
                if (!this.pageLoading) {
                  this.getOperatorList();
                }
                resolve();
              } else {
                this.$message.error("获取数据失败");
              }
            },
            { once: true }
          );
        } else {
          const res = await this.$store.dispatch("getPubDataList", params);
          if (res.status === 200) {
            if (!this.pageLoading) {
              this.getOperatorList();
            }
            this.fileDataList = res?.data?.data;
            resolve();
          }
        }
      });
    },
    // 文件上传确定后保存算子id
    // saveProcessId(data) {
    //   this.currentProcessId = data.id;
    // },
    // 渲染动态算子
    async renderOperator() {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/feOperator/getTree",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(
                { canvasId: _self.$route.query.id },
                { indices: false }
              ),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.getFileDataList();
              result.data.forEach((item) => {
                _self.renderData(item);
                // 暂时的写法只支持一个文件上传
                _self.currentProcessId = result.data[0].id;
              });
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/feOperator/getTree",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify({ canvasId: this.$route.query.id }, { indices: false }),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            console.log(res.data, e.data.webInfo.requestId === uuid);
            // TODO： 定制后台数据处理
            if (res.status === 200 && e.data.webInfo.requestId === uuid) {
              this.getFileDataList();
              res.data.forEach((item) => {
                this.renderData(item);
                // 暂时的写法只支持一个文件上传
                this.currentProcessId = res.data[0].id;
              });
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch(
          "renderOperatorByCanvasId",
          this.$route.query.id
        );
        if (res.data.status === 200) {
          this.getFileDataList();
          res.data.data.forEach((item) => {
            this.renderData(item);
            // 暂时的写法只支持一个文件上传
            this.currentProcessId = res.data.data[0].id;
          });
        }
      }
    },
    // 递归渲染
    renderData(item) {
      this.dynamicOperatorList.push(item);
      if (item.children.length === 0) return;
      this.renderData(item.children[0]);
    },
  },
  created() {
    // 每次进入清除上次的运行日志
    this.$store.commit("CLEAR_CODE");
    // 根据画布id回显动态链中算子
    this.renderOperator();
    // 左边控件区初始化
    // setTimeout(() => {
    //   this.getOperatorList();
    // }, 500);
    // 提前获取控件中处理方式的所有下拉选项
    // setTimeout(() => {
    //   this.getConditionSelection();
    // }, 1000);
  },
};
</script>

<style scoped lang="scss">
.el-row {
  height: 100%;
}

.el-col {
  height: 100%;
}

.el-card {
  height: 100%;

  .button-box {
    display: flex;
    width: 100%;
    margin-top: 5px;

    ::v-deep .el-button {
      width: 100%;
    }
  }

  .button-group {
    display: flex;
    justify-content: flex-end;
    span {
      margin-right: 20px;
      font-size: 16px;
      font-weight: 700;
      line-height: 40px;
      white-space: nowrap;
    }
  }
}

.col-one {
  display: flex;
  flex-direction: column;
}

::v-deep .el-input-group__append button.el-button {
  color: #fff;
  background-color: #0c92e0;
  border-color: #0c92e0;
  border-radius: 0;
}

.operator-box {
  display: flex;
  margin-bottom: 5px;
  text-align: center;
  line-height: 40px;
  border: 1px solid #d9d9d9;
  border-radius: 5px;
  cursor: pointer;
  .operator {
    width: 150px;
    height: 40px;
    font-size: 14px;
    &:hover {
      background-color: #e7f4fc;
    }
  }

  .delete-operator {
    border-left: 1px solid #d9d9d9;
    width: 60px;
    height: 40px;
    &:hover {
      background-color: #e7f4fc;
    }
  }
}

.operator-active {
  background-color: #0c92e0;
}
.content ::v-deep .el-tabs__content {
  overflow-y: auto;
  height: 76vh;
}
</style>
